import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim/core/controller/group_invite_controller.dart';
import 'package:openim_common/openim_common.dart';
import 'package:synchronized/synchronized.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../../core/controller/app_controller.dart';
import '../../../core/controller/im_controller.dart';
import '../../../routes/app_navigator.dart';
import '../../contacts/select_contacts/select_contacts_logic.dart';
import '../../contacts/user_profile_panel/user_profile _panel_logic.dart';
import '../../conversation/conversation_logic.dart';
import '../chat_logic.dart';
import 'edit_name/edit_name_logic.dart';
import 'group_member_list/group_member_list_logic.dart';

class GroupSetupLogic extends GetxController {
  final imLogic = Get.find<IMController>();

  final chatLogic = Get.find<ChatLogic>(tag: GetTags.chat);
  final appLogic = Get.find<AppController>();
  final conversationLogic = Get.find<ConversationLogic>();
  final memberList = <GroupMembersInfo>[].obs;
  late Rx<ConversationInfo> conversationInfo;
  late Rx<GroupInfo> groupInfo;
  late Rx<GroupMembersInfo> myGroupMembersInfo;
  late StreamSubscription _guSub;
  late StreamSubscription _mASub;
  late StreamSubscription _mISub;
  late StreamSubscription _mDSub;
  late StreamSubscription _ccSub;
  late StreamSubscription _jasSub;
  late StreamSubscription _jdsSub;
  final lock = Lock();
  final isJoinedGroup = false.obs;
  final avatar = Rx<File?>(null);

  // 添加一个变量来控制是否显示更多成员
  final showAllMembers = false.obs;
  // 添加一个变量来控制是否显示所有群成员（新增）
  final showAllGroupMembers = true.obs;
  // 添加群人数显示控制变量
  final showGroupMemberCount = true.obs;
  // 获取群成员互加好友权限状态
  bool get allowMemberAddFriend => groupInfo.value.applyMemberFriend != 1;
  // 获取群禁言状态
  bool get isGroupMuted => groupInfo.value.status == 3; // 假设status=3表示群禁言
  // 群收费相关属性
  final groupFeeEnabled = false.obs;
  final groupFee = 0.0.obs;
// 获取群收费状态
  bool get isGroupFeeEnabled => groupFeeEnabled.value;
  /// 切换群收费状态
  void toggleGroupFee() async {
    if (!isOwner) {
      IMViews.showToast('只有群主可以设置群收费');
      return;
    }
    
    if (groupFeeEnabled.value) {
      // 关闭群收费
      await _disableGroupFee();
    } else {
      // 开启群收费，显示设置费用对话框
      await _showSetFeeDialog();
    }
  }
  /// 启用群收费
  Future<void> _enableGroupFee(double fee) async {
    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () => _updateGroupFeeSettings(true, fee),
      );
      
      groupFeeEnabled.value = true;
      groupFee.value = fee;
      
      IMViews.showToast('群收费设置成功，费用：\$${fee.toStringAsFixed(2)}'); // 修改为美元符号
    } catch (e) {
      IMViews.showToast('设置群收费失败：$e');
    }
  }
  
  /// 禁用群收费
  Future<void> _disableGroupFee() async {
    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () => _updateGroupFeeSettings(false, 0.0),
      );
      
      groupFeeEnabled.value = false;
      groupFee.value = 0.0;
      
      IMViews.showToast('已关闭群收费');
    } catch (e) {
      IMViews.showToast('关闭群收费失败：$e');
    }
  }
  
  /// 更新群收费设置到服务器
  Future<void> _updateGroupFeeSettings(bool enabled, double fee) async {
    // 构建扩展信息 JSON
    final Map<String, dynamic> exData = {
      'groupFee': {
        'enabled': enabled,
        'amount': fee,
        'updatedAt': DateTime.now().millisecondsSinceEpoch,
        'updatedBy': OpenIM.iMManager.userID,
      },
    };
    
    // 如果群信息已有 ex 数据，则合并
    if (groupInfo.value.ex != null && groupInfo.value.ex!.isNotEmpty) {
      try {
        final existingData = jsonDecode(groupInfo.value.ex!);
        if (existingData is Map<String, dynamic>) {
          existingData['groupFee'] = exData['groupFee'];
          exData.addAll(existingData);
        }
      } catch (e) {
        // 如果解析失败，使用新数据
      }
    }
    
    final exString = jsonEncode(exData);
    
    await _modifyGroupInfo(ex: exString);
    
    // 更新本地群信息
    groupInfo.update((val) {
      val?.ex = exString;
    });
  }
  
  /// 显示设置费用对话框
  Future<void> _showSetFeeDialog() async {
    final TextEditingController feeController = TextEditingController(
      text: groupFee.value > 0 ? groupFee.value.toString() : '',
    );
    
    final result = await Get.dialog<double>(
      AlertDialog(
        title: Text('设置进群费用'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('设置用户加入群聊需要支付的费用'),
            SizedBox(height: 16),
            TextField(
              controller: feeController,
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              decoration: InputDecoration(
                labelText: '费用金额（美元）',
                hintText: '请输入费用金额',
                prefixText: '\$ ',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final fee = double.tryParse(feeController.text);
              if (fee != null && fee > 0) {
                Get.back(result: fee);
              } else {
                IMViews.showToast('请输入有效的费用金额');
              }
            },
            child: Text('确定'),
          ),
        ],
      ),
    );
    
    if (result != null) {
      await _enableGroupFee(result);
    }
  }
   /// 加载群收费设置
  void _loadGroupFeeSettings() {
    if (groupInfo.value.ex != null && groupInfo.value.ex!.isNotEmpty) {
      try {
        final exData = jsonDecode(groupInfo.value.ex!);
        if (exData is Map<String, dynamic> && exData.containsKey('groupFee')) {
          final feeData = exData['groupFee'];
          if (feeData is Map<String, dynamic>) {
            groupFeeEnabled.value = feeData['enabled'] ?? false;
            groupFee.value = (feeData['amount'] ?? 0.0).toDouble();
          }
        }
      } catch (e) {
        // 解析失败，使用默认值
        groupFeeEnabled.value = false;
        groupFee.value = 0.0;
      }
    } else {
      groupFeeEnabled.value = false;
      groupFee.value = 0.0;
    }
  }
  // 切换群禁言状态
  void toggleGroupMute() async {
    if (!isOwnerOrAdmin) {
      IMViews.showToast('您没有权限设置群禁言');
      return;
    }
    
    try {
      final newMuteStatus = !isGroupMuted;
      await LoadingView.singleton.wrap(
        asyncFunction: () => OpenIM.iMManager.groupManager.changeGroupMute(
          groupID: groupInfo.value.groupID,
          mute: newMuteStatus,
        ),

      );
      
      // 更新本地状态
      groupInfo.update((val) {
        val?.status = newMuteStatus ? 3 : 0; // 3表示禁言，0表示正常
      });
      
      IMViews.showToast(newMuteStatus ? '开启群禁言' : '关闭群禁言');
    } catch (e) {
      IMViews.showToast('设置群禁言失败：$e');
    }
  }
  // 切换群成员互加好友权限
  void toggleAllowMemberAddFriend() async {
    try {
      final newValue = allowMemberAddFriend ? 1 : 0;
      await LoadingView.singleton.wrap(
        asyncFunction: () => _modifyGroupInfo(applyMemberFriend: newValue),
      );
      groupInfo.update((val) {
        val?.applyMemberFriend = newValue;
      });
      IMViews.showToast(newValue == 0 ? '已允许群成员互加好友' : '已禁止群成员互加好友');
    } catch (e) {
      IMViews.showToast('设置失败：$e');
    }
  }

  @override
  void onInit() async {
    if (Get.arguments['conversationInfo'] != null) {
      conversationInfo = Rx(Get.arguments['conversationInfo']);
    } else {
      final temp = await OpenIM.iMManager.conversationManager.getOneConversation(
          sourceID: chatLogic.conversationInfo.isGroupChat
              ? chatLogic.conversationInfo.groupID!
              : chatLogic.conversationInfo.userID!,
          sessionType: chatLogic.conversationInfo.conversationType!);
      conversationInfo = Rx(temp);
    }
    groupInfo = Rx(_defaultGroupInfo);
    myGroupMembersInfo = Rx(_defaultMemberInfo);

    // 监听群组信息变化，从ex字段读取群人数显示设置
    groupInfo.listen((info) {
      if (info.ex != null && info.ex!.isNotEmpty) {
        try {
          final exData = jsonDecode(info.ex!);
          if (exData.containsKey('showGroupMemberCount')) {
            showGroupMemberCount.value = exData['showGroupMemberCount'] ?? true;
          }
        } catch (e) {
          print('Error parsing group ex data: $e');
        }
      }
    });

    _ccSub = imLogic.conversationChangedSubject.listen((newList) {
      final newValue =
          newList.firstWhereOrNull((element) => element.conversationID == conversationInfo.value.conversationID);
      if (newValue != null) {
        conversationInfo.update((val) {
          val?.isPinned = newValue.isPinned;
          val?.recvMsgOpt = newValue.recvMsgOpt;
          val?.isMsgDestruct = newValue.isMsgDestruct;
          val?.msgDestructTime = newValue.msgDestructTime;
        });
      }
    });

    _guSub = imLogic.groupInfoUpdatedSubject.listen((value) {
      if (value.groupID == groupInfo.value.groupID) {
        _updateGroupInfo(value);
      }
    });

    _jasSub = imLogic.joinedGroupAddedSubject.listen((value) {
      if (value.groupID == groupInfo.value.groupID) {
        isJoinedGroup.value = true;
        _queryAllInfo();
      }
    });

    _jdsSub = imLogic.joinedGroupDeletedSubject.listen((value) {
      if (value.groupID == groupInfo.value.groupID) {
        isJoinedGroup.value = false;
      }
    });
   
    _mISub = imLogic.memberInfoChangedSubject.listen((e) {
      if (e.groupID == groupInfo.value.groupID && e.userID == myGroupMembersInfo.value.userID) {
        myGroupMembersInfo.update((val) {
          val?.nickname = e.nickname;
          val?.roleLevel = e.roleLevel;
        });
      }
      
      if (e.groupID == groupInfo.value.groupID) {
        if (showAllGroupMembers.value) {
          // 显示所有成员模式：更新任何成员信息
          if (e.userID == groupInfo.value.ownerUserID) {
            var index = memberList.indexWhere((element) => element.userID == groupInfo.value.ownerUserID);
            if (index == -1) {
              memberList.insert(0, e);
            } else if (index != 0) {
              memberList.insert(0, memberList.removeAt(index));
            }
          } else {
            var index = memberList.indexWhere((element) => element.userID == e.userID);
            if (index != -1) {
              memberList[index] = e;
            } else {
              memberList.add(e);
            }
          }
        } else {
          // 只显示管理员模式：只处理群主和管理员
          if (e.roleLevel == GroupRoleLevel.owner || e.roleLevel == GroupRoleLevel.admin) {
            if (e.userID == groupInfo.value.ownerUserID) {
              var index = memberList.indexWhere((element) => element.userID == groupInfo.value.ownerUserID);
              if (index == -1) {
                memberList.insert(0, e);
              } else if (index != 0) {
                memberList.insert(0, memberList.removeAt(index));
              }
            } else {
              var index = memberList.indexWhere((element) => element.userID == e.userID);
              if (index != -1) {
                memberList[index] = e;
              } else {
                memberList.add(e);
              }
            }
          } else {
            // 如果成员被降级为普通成员，从列表中移除
            memberList.removeWhere((element) => element.userID == e.userID);
          }
        }
      }
      
      memberList.sort((a, b) {
        if (b.roleLevel != a.roleLevel) {
          return b.roleLevel!.compareTo(a.roleLevel!);
        } else {
          return b.joinTime!.compareTo(a.joinTime!);
        }
      });
  });
   
    _mASub = imLogic.memberAddedSubject.listen((e) async {
      if (e.groupID == groupInfo.value.groupID) {
        if (e.userID == OpenIM.iMManager.userID) {
          isJoinedGroup.value = true;
          _queryAllInfo();
        } else {
          if (showAllGroupMembers.value) {
            // 显示所有成员时，添加任何新成员
            memberList.add(e);
          } else {
            // 只显示管理员时，只添加群主和管理员
            if (e.roleLevel == GroupRoleLevel.owner || e.roleLevel == GroupRoleLevel.admin) {
              memberList.add(e);
            }
          }
        }
      }
    });
    
    _mDSub = imLogic.memberDeletedSubject.listen((e) {
      if (e.groupID == groupInfo.value.groupID) {
        if (e.userID == OpenIM.iMManager.userID) {
          isJoinedGroup.value = false;
        } else {
          memberList.removeWhere((element) => element.userID == e.userID);
        }
      }
    });
    // 初始化群人数显示设置
    showGroupMemberCount.value = DataSp.getShowGroupMemberCount();
    super.onInit();
  }
    // 切换群人数显示
  void toggleShowGroupMemberCount(bool value) async {
    if (!isOwnerOrAdmin) {
      IMViews.showToast('您没有权限设置群人数显示');
      return;
    }

    try {
      // 获取当前群组的ex字段
      final currentEx = groupInfo.value.ex ?? '{}';
      Map<String, dynamic> exData;
      
      try {
        exData = jsonDecode(currentEx);
      } catch (e) {
        exData = {};
      }
      
      // 更新ex字段中的群人数显示设置
      exData['showGroupMemberCount'] = value;
      final newEx = jsonEncode(exData);

      // 更新服务器设置，使用ex字段保存设置
      await LoadingView.singleton.wrap(
        asyncFunction: () => _modifyGroupInfo(ex: newEx),
      );

      // 更新本地变量
      showGroupMemberCount.value = value;
      
      // 更新本地群组信息
      groupInfo.update((val) {
        val?.ex = newEx;
      });

      // 通知ChatLogic更新群人数显示
      try {
        final chatLogic = Get.find<ChatLogic>(tag: GetTags.chat);
        chatLogic.updateShowGroupMemberCount(showGroupMemberCount.value);
      } catch (e) {
        // ChatLogic可能不存在，忽略错误
      }

      IMViews.showToast(value ? '已开启群人数显示' : '已关闭群人数显示');
    } catch (e) {
      IMViews.showToast('设置失败：$e');
    }
  }
  @override
  void onReady() {
    _checkIsJoinedGroup();
    super.onReady();
  }

  @override
  void onClose() {
    _guSub.cancel();
    _mASub.cancel();
    _mDSub.cancel();
    _ccSub.cancel();
    _mISub.cancel();
    _jdsSub.cancel();
    _jasSub.cancel();
    super.onClose();
  }

  get _defaultGroupInfo => GroupInfo(
        groupID: conversationInfo.value.groupID!,
        groupName: conversationInfo.value.showName,
        faceURL: conversationInfo.value.faceURL,
        memberCount: 0,
      );

  get _defaultMemberInfo => GroupMembersInfo(
        userID: OpenIM.iMManager.userID,
        nickname: OpenIM.iMManager.userInfo.nickname,
      );

  bool get isOwnerOrAdmin => isOwner || isAdmin;

  bool get isAdmin => myGroupMembersInfo.value.roleLevel == GroupRoleLevel.admin;

  bool get isNotDisturb => conversationInfo.value.recvMsgOpt != 0;

  bool get isOwner => groupInfo.value.ownerUserID == OpenIM.iMManager.userID;

  String get conversationID => conversationInfo.value.conversationID;

  void _checkIsJoinedGroup() async {
    isJoinedGroup.value = await OpenIM.iMManager.groupManager.isJoinedGroup(
      groupID: groupInfo.value.groupID,
    );
    _queryAllInfo();
  }

  void _queryAllInfo() {
    if (isJoinedGroup.value) {
      getGroupInfo();
      getGroupMembers();
      getMyGroupMemberInfo();
    }
  }

    getGroupMembers() async {
    // 获取所有成员
    var allMembers = await OpenIM.iMManager.groupManager.getGroupMemberList(
      groupID: groupInfo.value.groupID,
      count: 1000,
    );
    
    // 预加载群成员的好友备注信息
    try {
      await IMUtils.preloadGroupMemberRemarks(allMembers);
    } catch (e) {
      print('预加载群成员好友备注失败: $e');
    }

    // 域后端资料富化
    final enrichedAll = await _enrichMembersWithDomain(allMembers);
    
    if (showAllGroupMembers.value) {
      memberList.assignAll(enrichedAll);
    } else {
      var filteredMembers = enrichedAll.where((member) {
        return member.roleLevel == GroupRoleLevel.owner || 
               member.roleLevel == GroupRoleLevel.admin;
      }).toList();
      memberList.assignAll(filteredMembers);
    }
  }

  Future<List<GroupMembersInfo>> _enrichMembersWithDomain(List<GroupMembersInfo> members) async {
    final tasks = <Future<void>>[];
    for (final m in members) {
      final uid = m.userID;
      if (uid != null && uid.isNotEmpty) {
        final cached = UserCacheManager().getUserInfo(uid);
        if (cached != null) {
          m.faceURL = cached.faceURL ?? m.faceURL;
          m.nickname = cached.nickname ?? m.nickname;
          continue;
        }
        tasks.add(() async {
          try {
            final profile = await Apis.getUserProfileByOpenIMID(uid);
            if (profile != null) {
              m.faceURL = profile.faceURL ?? m.faceURL;
              m.nickname = profile.nickname ?? m.nickname;
              UserCacheManager().addOrUpdateUserInfo(uid, profile);
            }
          } catch (_) {}
        }());
      }
    }
    await Future.wait(tasks);
    return members;
  }

  getGroupInfo() async {
    var list = await OpenIM.iMManager.groupManager.getGroupsInfo(
      groupIDList: [groupInfo.value.groupID],
    );
    var value = list.firstOrNull;
    if (null != value) {
      _updateGroupInfo(value);
    }
  }

  getMyGroupMemberInfo() async {
    final list = await OpenIM.iMManager.groupManager.getGroupMembersInfo(
      groupID: groupInfo.value.groupID,
      userIDList: [OpenIM.iMManager.userID],
    );
    final info = list.firstOrNull;
    if (null != info) {
      myGroupMembersInfo.update((val) {
        val?.nickname = info.nickname;
        val?.roleLevel = info.roleLevel;
      });
    }
  }

  void _updateGroupInfo(GroupInfo value) {
    groupInfo.update((val) {
      val?.groupName = value.groupName;
      val?.faceURL = value.faceURL;
      val?.notification = value.notification;
      val?.introduction = value.introduction;
      val?.memberCount = value.memberCount;
      val?.ownerUserID = value.ownerUserID;
      val?.status = value.status;
      val?.needVerification = value.needVerification;
      val?.groupType = value.groupType;
      val?.lookMemberInfo = value.lookMemberInfo;
      val?.applyMemberFriend = value.applyMemberFriend;
      val?.notificationUserID = value.notificationUserID;
      val?.notificationUpdateTime = value.notificationUpdateTime;
      val?.ex = value.ex;
    });
    // 加载群收费设置
    _loadGroupFeeSettings();
      // 加载成员可见性设置
    _loadMemberVisibilitySetting();
  }

    void _loadMemberVisibilitySetting() {
    bool showAll = true;
    if (groupInfo.value.ex != null && groupInfo.value.ex!.isNotEmpty) {
      try {
        final data = jsonDecode(groupInfo.value.ex!);
        if (data is Map<String, dynamic>) {
          if (data['memberVisibility'] is Map<String, dynamic>) {
            final mv = data['memberVisibility'] as Map<String, dynamic>;
            if (mv['showAllGroupMembers'] is bool) {
              showAll = mv['showAllGroupMembers'] as bool;
            }
          } else if (data['showAllGroupMembers'] is bool) {
            // 兼容旧字段
            showAll = data['showAllGroupMembers'] as bool;
          }
        }
      } catch (_) {}
    }
    showAllGroupMembers.value = showAll;
  }

  void modifyGroupAvatar() async {
    final List<AssetEntity>? assets = await AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: const AssetPickerConfig(maxAssets: 1, requestType: RequestType.image),
    );
    if (assets != null) {
      final file = await assets.first.file;
      final result = await IMViews.uCropPic(file!.path);

      final path = result['path'];
      final url = result['url'];

      if (url != null) {
        avatar.value = File(path);
        await _modifyGroupInfo(faceUrl: url);
        groupInfo.update((val) {
          val?.faceURL = url;
        });
      }
    }
  }

    void modifyGroupName(String? faceUrl) => AppNavigator.startEditGroupName(
        type: EditNameType.groupNickname,
        faceUrl: faceUrl,
      );
      void editGroupIntroduction() async {
        final controller = TextEditingController(text: groupInfo.value.introduction ?? '');
        int currentLength = controller.text.length;

        final result = await Get.dialog<String>(
          Dialog(
            backgroundColor: Styles.c_FFFFFF,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
            insetPadding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 24.h),
            child: StatefulBuilder(
              builder: (context, setState) {
                return Container(
                  padding: EdgeInsets.all(16.w),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 标题
                      Row(
                        children: [
                          Icon(Icons.info_outline, color: Styles.c_0089FF, size: 20.w),
                          8.horizontalSpace,
                          Text('编辑群简介', style: Styles.ts_0C1C33_17sp_medium),
                          const Spacer(),
                          GestureDetector(
                            onTap: () => Get.back(),
                            child: Icon(Icons.close, size: 18.w, color: Styles.c_8E9AB0),
                          ),
                        ],
                      ),
                      12.verticalSpace,
                      // 文本输入
                      TextField(
                        controller: controller,
                        maxLines: 6,
                        maxLength: 200,
                        onChanged: (text) => setState(() => currentLength = text.length),
                        decoration: InputDecoration(
                          hintText: '请输入群简介，最多200字',
                          hintStyle: Styles.ts_8E9AB0_14sp,
                          filled: true,
                          fillColor: Styles.c_F8F9FA,
                          contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.r),
                            borderSide: BorderSide(color: Styles.c_E8EAEF, width: 1.w),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8.r),
                            borderSide: BorderSide(color: Styles.c_0089FF, width: 1.w),
                          ),
                          counterText: '$currentLength/200',
                          counterStyle: Styles.ts_8E9AB0_12sp,
                        ),
                      ),
                      8.verticalSpace,
                      // 提示文案
                      Row(
                        children: [
                          Icon(Icons.lightbulb_outline, size: 14.w, color: Styles.c_FFB300),
                          6.horizontalSpace,
                          Expanded(
                            child: Text(
                              '建议填写群主题、规则或近期活动简介，提升群形象和参与度。',
                              style: Styles.ts_8E9AB0_12sp,
                            ),
                          ),
                        ],
                      ),
                      14.verticalSpace,
                      // 操作按钮
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          TextButton(
                            onPressed: () => Get.back(),
                            child: Text('取消', style: Styles.ts_8E9AB0_14sp),
                          ),
                          8.horizontalSpace,
                          ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              elevation: 0,
                              backgroundColor: Styles.c_FFB300,
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.r)),
                              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
                            ),
                            onPressed: () {
                              final text = controller.text.trim();
                              if (text.isEmpty) {
                                IMViews.showToast('请输入群简介内容');
                                return;
                              }
                              Get.back(result: text);
                            },
                            child: Text('保存', style: Styles.ts_FFFFFF_14sp),
                          ),
                        ],
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        );

        if (result != null) {
          try {
            await LoadingView.singleton.wrap(
              asyncFunction: () => _modifyGroupInfo(introduction: result),
            );
            groupInfo.update((val) {
              val?.introduction = result;
            });
            IMViews.showToast('群简介修改成功');
          } catch (e) {
            IMViews.showToast('群简介修改失败：$e');
          }
        }
      }

    
  _modifyGroupInfo({
    String? groupName,
    String? notification,
    String? introduction,
    String? faceUrl,
    int? applyMemberFriend, // 新增参数
    String? ex, // 添加 ex 参数用于存储扩展信息
  }) =>
     OpenIM.iMManager.groupManager.setGroupInfo(GroupInfo(
        groupID: groupInfo.value.groupID,
        groupName: groupName,
        notification: notification,
        introduction: introduction,
        faceURL: faceUrl,
        applyMemberFriend: applyMemberFriend, // 新增字段
        ex: ex, // 添加 ex 字段
      ));

  void viewGroupQrcode() => AppNavigator.startGroupQrcode();

  void viewGroupMembers() => AppNavigator.startGroupMemberList(
        groupInfo: groupInfo.value,
      );

  void groupManage() => AppNavigator.startGroupManage(
        groupInfo: groupInfo.value,
      );

  void _removeConversation() async {
    await OpenIM.iMManager.conversationManager.deleteConversationAndDeleteAllMsg(
      conversationID: conversationInfo.value.conversationID,
    );
    
    // 从会话列表中移除该会话
    final conversationLogic = Get.find<ConversationLogic>();
    conversationLogic.list.removeWhere((e) => e.conversationID == conversationInfo.value.conversationID);
    conversationLogic.update();
  }

  void quitGroup() async {
    if (isJoinedGroup.value) {
      if (isOwner) {
        var confirm = await Get.dialog(CustomDialog(
          title: StrRes.dismissGroupHint,
        ));
        if (confirm == true) {
          try {
            // 1. 解散群聊
            await OpenIM.iMManager.groupManager.dismissGroup(
              groupID: groupInfo.value.groupID,
            );
            
            IMViews.showToast('群聊已解散');
          } catch (e) {
            IMViews.showToast('解散群聊失败：$e');
            return;
          }
        } else {
          return;
        }
      } else {
        var confirm = await Get.dialog(CustomDialog(
          title: StrRes.quitGroupHint,
        ));
        if (confirm == true) {
          await OpenIM.iMManager.groupManager.quitGroup(
            groupID: groupInfo.value.groupID,
          );
        } else {
          return;
        }
      }
    } else {
      // 用户未加入群聊时，清空聊天记录并删除会话
      await _clearChatHistoryAndDeleteConversation();
    }

    AppNavigator.startBackMain();
  }

  // 清空聊天记录并删除会话的私有方法
  Future<void> _clearChatHistoryAndDeleteConversation() async {
    try {
      // 清空聊天记录并删除会话
      await OpenIM.iMManager.conversationManager.deleteConversationAndDeleteAllMsg(
        conversationID: conversationID,
      );
      
      // 清空聊天页面的消息列表
      chatLogic.clearAllMessage();
      
      // 从会话列表中删除该会话
      final conversationLogic = Get.find<ConversationLogic>();
      conversationLogic.list.removeWhere((e) => e.conversationID == conversationInfo.value.conversationID);
      conversationLogic.update();
      
    } catch (e) {
      print('清空聊天记录和删除会话失败：$e');
      // 即使清空失败，也不阻止后续流程
    }
  }

  void copyGroupID() {
    IMUtils.copy(text: groupInfo.value.groupID);
  }

  // 修改 length 方法
  int length() {
    int maxDisplayCount = 8; // 最多显示8个成员
    int buttons = isOwnerOrAdmin ? 1 : 1; // 只保留添加按钮
    
    if (showAllMembers.value) {
      // 显示所有成员时
      return memberList.length + buttons;
    } else {
      // 限制显示数量时
      int totalItems = memberList.length + buttons;
      if (memberList.length > maxDisplayCount) {
        return maxDisplayCount + buttons + 1; // +1 为"显示更多"按钮
      } else {
        return totalItems;
      }
    }
  }

  Widget itemBuilder({
    required int index,
    required Widget Function(GroupMembersInfo info) builder,
    required Widget Function() addButton,
    required Widget Function() delButton,
    required Widget Function() showMoreButton, // 添加 showMoreButton 参数
  })  {
    int maxDisplayCount = 8;
    
    if (showAllMembers.value) {
      // 显示所有成员模式
      if (index < memberList.length) {
        var info = memberList.elementAt(index);
        return builder(info);
      } else if (index == memberList.length) {
        return addButton();
      }
    } else {
      // 限制显示模式
      if (memberList.length > maxDisplayCount) {
        if (index < maxDisplayCount) {
          var info = memberList.elementAt(index);
          return builder(info);
        } else if (index == maxDisplayCount) {
          return addButton();
        } else if (index == maxDisplayCount + 1) {
          return showMoreButton();
        }
      } else {
        if (index < memberList.length) {
          var info = memberList.elementAt(index);
          return builder(info);
        } else if (index == memberList.length) {
          return addButton();
        }
      }
    }
    return Container(); // 默认返回空容器
  }
 // 添加切换显示更多的方法
  void toggleShowAllMembers() {
    showAllMembers.value = !showAllMembers.value;
  }
  // 切换群成员显示模式
  Future<void> toggleShowAllGroupMembers(bool value) async {
    if (!isOwnerOrAdmin) {
      IMViews.showToast('您没有权限设置成员显示');
      return;
    }
    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () => _updateMemberVisibilitySetting(value),
      );
      showAllGroupMembers.value = value;
      getGroupMembers();
    } catch (e) {
      IMViews.showToast('设置失败：$e');
    }
  }

    Future<void> _updateMemberVisibilitySetting(bool showAll) async {
    Map<String, dynamic> exData = {};
    if (groupInfo.value.ex != null && groupInfo.value.ex!.isNotEmpty) {
      try {
        final existing = jsonDecode(groupInfo.value.ex!);
        if (existing is Map<String, dynamic>) {
          exData = existing;
        }
      } catch (_) {}
    }
    exData['memberVisibility'] = {
      'showAllGroupMembers': showAll,
      'updatedAt': DateTime.now().millisecondsSinceEpoch,
      'updatedBy': OpenIM.iMManager.userID,
    };
    final exString = jsonEncode(exData);
    await _modifyGroupInfo(ex: exString);
    groupInfo.update((val) {
      val?.ex = exString;
    });
  }
  
  addMember() async {
    final result = await AppNavigator.startSelectContacts(
      action: SelAction.addMember,
      groupID: groupInfo.value.groupID,
    );

    final list = IMUtils.convertSelectContactsResultToUserID(result);
    if (list is List<String>) {
      try {
        await LoadingView.singleton.wrap(
          asyncFunction: () => OpenIM.iMManager.groupManager.inviteUserToGroup(
            groupID: groupInfo.value.groupID,
            userIDList: list,
            reason: 'Come on baby',
          ),
        );
      } catch (_) {}
      getGroupMembers();
    }
  }

  removeMember() async {
    final list = await AppNavigator.startGroupMemberList(
      groupInfo: groupInfo.value,
      opType: GroupMemberOpType.del,
    );
    if (list is List<GroupMembersInfo>) {
      var removeUidList = list.map((e) => e.userID!).toList();
      try {
        await LoadingView.singleton.wrap(
          asyncFunction: () => OpenIM.iMManager.groupManager.kickGroupMember(
            groupID: groupInfo.value.groupID,
            userIDList: removeUidList,
            reason: 'Get out baby',
          ),
        );
      } catch (_) {}
      getGroupMembers();
    }
  }

  void viewMemberInfo(GroupMembersInfo membersInfo) => AppNavigator.startUserProfilePane(
        userID: membersInfo.userID!,
        nickname: membersInfo.nickname,
        faceURL: membersInfo.faceURL,
        groupID: membersInfo.groupID,
      );

    // 编辑群公告
  void editGroupAnnouncement() {
    // 这里可以导航到群公告编辑页面
    AppNavigator.startEditGroupAnnouncement();
  }

    // 新增：查看群公告方法
  void viewGroupAnnouncement() {
    if (isOwnerOrAdmin) {
      // 管理员可以编辑
      editGroupAnnouncement();
    } else {
      // 普通成员只能查看
      _showAnnouncementDialog();
    }
  }

    // 显示群公告查看对话框
  void _showAnnouncementDialog() {
    final announcement = groupInfo.value.notification?.isNotEmpty == true 
        ? groupInfo.value.notification! 
        : '暂无群公告';
        
    Get.dialog(
      AlertDialog(
        title: Row(
          children: [
            Icon(Icons.campaign, color: Styles.c_0089FF, size: 20.w),
            8.horizontalSpace,
            Text('群公告'),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          constraints: BoxConstraints(
            maxHeight: 300.h,
          ),
          child: SingleChildScrollView(
            child: Text(
              announcement,
              style: Styles.ts_0C1C33_14sp,
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('知道了'),
          ),
        ],
      ),
    );
  }

  // 切换免打扰状态
  void toggleNotDisturb() async {
    final newValue = isNotDisturb ? 0 : 1;
    final req = ConversationReq(recvMsgOpt: newValue);
    await OpenIM.iMManager.conversationManager.setConversation(
      conversationID,
      req,
    );
  }

  // 切换置顶状态
  void toggleTopConversation() async {
    final newValue = !(conversationInfo.value.isPinned ?? false);
    await OpenIM.iMManager.conversationManager.pinConversation(
      conversationID: conversationID,
      isPinned: newValue,
    );
  }

  // 清空聊天记录
  void clearChatHistory() async {
    var confirm = await Get.dialog(const CustomDialog(
      title: '确定要清空聊天记录吗？',
    ));
    if (confirm == true) {
      try {
        await OpenIM.iMManager.conversationManager.clearConversationAndDeleteAllMsg(
          conversationID: conversationID,
        );
        // 清空聊天页面的消息列表
        chatLogic.clearAllMessage();
        IMViews.showToast('聊天记录已清空');
      } catch (e) {
        IMViews.showToast('清空失败：$e');
      }
    }
  }

    // 查找聊天记录
  void searchChatHistory() async {
    // 使用聊天历史搜索功能并处理返回结果
    final result = await AppNavigator.startChatHistorySearch(
      conversationID: conversationInfo.value.conversationID,
      conversationInfo: conversationInfo.value,
    );
    
    // 处理搜索返回的结果
    if (result != null && result is Map<String, dynamic>) {
      final action = result['action'];
      
      if (action == 'jumpToMessage') {
        final message = result['message'] as Message?;
        
        if (message != null) {
          // 返回到聊天页面并传递搜索消息
          Get.back(result: {
            'action': 'jumpToMessage',
            'message': message,
          });
        }
      }
    }
  }

  // 生成群聊邀请深度链接
  String generateGroupInviteLink() {
    return GroupInviteController.generateGroupInviteLink(
      groupId: groupInfo.value.groupID,
      inviterUserId: OpenIM.iMManager.userID,
    );
  }

  // 生成群聊邀请自定义scheme链接
  String generateGroupInviteSchemeLink() {
    return GroupInviteController.generateCustomSchemeLink(
      groupId: groupInfo.value.groupID,
      inviterUserId: OpenIM.iMManager.userID,
    );
  }

    // 复制群聊邀请链接（优先复制服务端返回的网页链接）
    Future<void> copyGroupInviteLink() async {
      final link = generateGroupInviteSchemeLink();
      // 请求服务端生成网页链接
      final pageUrl = await GroupInviteController.to.submitGeneratedInviteLink(
        link,
        groupInfo.value.groupID,
        OpenIM.iMManager.userID,
      );
      if (pageUrl != null && pageUrl.isNotEmpty) {
        IMUtils.copy(text: pageUrl);
        IMViews.showToast('群聊邀请网页链接已复制');
      } else {
        // 回退：复制原始深度链接
        IMUtils.copy(text: link);
        IMViews.showToast('已复制原始深度链接');
      }
    }

   // 获取群聊邀请链接的显示文本（截取部分用于显示）
  String getGroupInviteLinkDisplay() {
    final groupId = groupInfo.value.groupID;
    // 只显示简化的链接格式，避免过长
    return 'paxiy.app/group/invite?id=${groupId.length > 8 ? groupId.substring(0, 8) : groupId}...';
  }
}
